#!/usr/bin/python

import gdata.youtube.service

youtube_service = gdata.youtube.service.YouTubeService()

class VideoEntry(object):
    def __init__(self, title=None, description=None):
        self.title = title
        self.description = description
        self.thumbnails = None
        self.duration_seconds = 0

    def __str__(self):
        txt = 'Video: %s\nDescription: %s\nDuration: %d seconds\nThumnails: %s\n' % \
                (self.title, self.description, self.duration_seconds, self.thumbnails)
        return txt

    @staticmethod
    def createFromGDataVideoEntry(entry):
        video = VideoEntry(entry.title.text, entry.description.text)
        video.thumbnails = [thumbnail.url for thumbnail in entry.media.thumbnail]
        video.duration_seconds = int(entry.media.duration.seconds)
        return video


class Playlist(object):
    def __init__(self, name=None, description=None, uri=None):
        self.name = name
        self.description = description
        self.uri = uri
        self.video_entries = []

    def load_video_entries(self):
        playlist_feed = youtube_service.GetYouTubePlaylistVideoFeed(uri=self.uri)
        self.video_entries = []
        for entry in playlist_feed.entry:
            video = VideoEntry.createFromGDataVideoEntry(entry)
            self.video_entries.append(video)

    def __str__(self):
        txt = 'Playlist: %s\nDescription: %s\nUri: %s\n' % (self.name, self.description, self.uri)
        for video_entry in self.video_entries:
            txt += str(video_entry) + '\n'
        return txt

    @staticmethod
    def createFromGDataPlaylistEntry(playlist):
        return Playlist(playlist.title.text, playlist.description.text, playlist.feed_link[0].href)


def loadPlaylists():
    playlist_feed = youtube_service.GetYouTubePlaylistFeed(username='khanacademy')
    playlists = []
    for playlist_entry in playlist_feed.entry:
        playlists.append(Playlist.createFromGDataPlaylistEntry(playlist_entry))
    return playlists


if __name__ == '__main__':
    playlists = loadPlaylists()
    for pl in playlists:
        print pl

